package com.winning.zjjh.utils;

import org.apache.commons.lang.StringUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

/**
 * @Author: xkh@winning.com.cn
 * @Desc: TODO
 * @Date: 2019-03-19 13:22
 **/
public class JAXBUtils {

    private static DocumentBuilderFactory documentBuilderFactory;
    private static DocumentBuilder documentBuilder;


    public static JAXBContext createJAXBContext(Class cla) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(cla);
        return context;
    }

    public static Marshaller createMarshaller(Class cla) throws JAXBException {
        JAXBContext jaxbContext = createJAXBContext(cla);
        Marshaller marshaller = jaxbContext.createMarshaller();
        return marshaller;
    }

    public static Unmarshaller createUnMarshaller(Class cla) throws JAXBException {
        JAXBContext jaxbContext = createJAXBContext(cla);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return unmarshaller;
    }

    public static Marshaller createMarshaller(JAXBContext jaxbContext) throws JAXBException {
        Marshaller marshaller = jaxbContext.createMarshaller();
        return marshaller;
    }

    public static Unmarshaller createUnMarshaller(JAXBContext jaxbContext) throws JAXBException {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return unmarshaller;
    }

    public static String replaceNameSpace(String source,String regex) {
        if (StringUtils.isEmpty(regex)) {
            regex ="(\\s{1}xmlns:xsi=\\\"[a-zA-Z:/.0-9-]+\\\"\\s{1}xsi:nil=\\\"[true]+\\\")|(\\s{1}xsi:nil=\\\"[true]+\\\"\\s{1}xmlns:xsi=\\\"[a-zA-Z:/.0-9-]+\\\")";
        }
        return source.replaceAll(regex,"");
    }

    public static DocumentBuilderFactory getDocumentBuilderFactory() {
        return documentBuilderFactory == null ? DocumentBuilderFactory.newInstance() : documentBuilderFactory;
    }

    public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
        return documentBuilder == null ? getDocumentBuilderFactory().newDocumentBuilder() : documentBuilder;
    }


}
